package com.cat.dataStructure;

import java.util.HashMap;
import java.util.Map;

/**
*   @description https://leetcode.cn/problems/contiguous-array/
*   @author 曲大人的喵
*   @create 2025/8/16 17:07
*   @since JDK17
*/

public class Solution29 {
    static HashMap<Integer, Integer> map = new HashMap<>();
    public int findMaxLength(int[] nums) {
        map.clear();
        map.put(0, -1);
        int n = nums.length, ans = 0, sum = 0;
        for (int i = 0; i < n; i++) {
            nums[i] = nums[i] == 1 ? 1 : -1;
        }

        for (int i = 0; i < n; i++) {
            sum += nums[i];
            if (map.containsKey(sum)) {
                ans = Math.max(ans, i - map.get(sum));
            } else {
                map.put(sum, i);
            }
        }
        return ans;
    }
}
